package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("access_token");
        //如果token为null
        if (accessToken==null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_AUTH);//发送请求的客户端没有登录
        }else{//token是存在的，使用JwtUtil.parseToken(accessToken) 解析验证token是否过期
            Claims claims = JwtUtil.parseToken(accessToken);

            Long userId = claims.get("userId", Long.class);
            String userName = claims.get("userName", String.class);
//            //把负载数据保存到请求域中
//            request.setAttribute("userId",userId);
            //把负载数据保存到线程中
//            ThreadLocal threadLocal = new ThreadLocal();
//            threadLocal.set(userId);
            LoginUserContext.setUser(new LoginUser(userId,userName));
        }

        System.out.println("拦截你！！！");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.removeUser();
    }
}
